<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.key" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getData()"><i class="el-icon-search el-icon--left"></i>搜索
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <!-- 上传 -->
          <el-upload
            class="upload-demo"
            :action="uploadAction"
            :show-file-list="false"
            :multiple="false"
            :limit="1"
            :onError="uploadError"
            :onSuccess="uploadSuccess"
            :beforeUpload="beforeAvatarUpload">
            <el-button type="primary" :loading="uploadLoading">上传<i class="el-icon-upload el-icon--right"></i></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="handleDownload('batch')" :loading="batchDownloadLoading">导出选中
          </el-button>
          <el-button type="primary" v-on:click="handleDownload('all')" :loading="allDownloadLoading">导出全部
          </el-button>
          <el-button type="success" v-on:click="handleDownload('base')" :loading="baseDownloadLoading">下载模板
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table :data="data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" border
              style="width: 100%;">
      <el-table-column type="selection" min-width="55">
      </el-table-column>
      <el-table-column prop="fieldId" label="试验田序号Test" min-width="240" :show-overflow-tooltip="true" fixed>
      </el-table-column>
      <el-table-column prop="name" label="试验田名称Test" min-width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="experimentName" label="试验类型Test" min-width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="操作" min-width="140" fixed="right">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-button type="primary" v-on:click="handleDownload('batch')" :disabled="this.sels.length===0"
                 :loading="batchDownloadLoading">导出选中
      </el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="limit"
                     :total="total" style="float:right;">
      </el-pagination>
    </el-col>
  </section>
</template>

<script>
  //import util from '../../common/js/util'
  //import NProgress from 'nprogress'
  //import {getDataListPage, removeData, batchRemoveData, editData, addData} from '../../api/api';

  // 把getFieldList接口导入进来；

  import { getFieldList, editField, addField, deleteField } from '@/api/FarmlandManage'
  import { getExperimentTypes } from '../../api/FarmlandManage'

  export default {
    data() {
      return {
        filters: {
          key: '',
        },
        data: [],
        total: 0,
        limit: 10,
        page: 1,
        listLoading: false,
        uploadLoading: false,
        allDownloadLoading: false,
        batchDownloadLoading: false,
        baseDownloadLoading: false,
        sels: [], //列表选中列
        uploadAction:'',
        dataList: [],
        baseUpload: [
          {
            fieldId: '',
            name: '',
            experimentName: ''
          }
        ],

        farmlandMsg: {
          name: '',
          remark: '',
          experimentName: '',
          shotId: '',
          rowAmount: '',
          columnAmount: '',
        }
      }
    },

    //二、类似于构造方法；
    created() {
      this.fetchData()
      // for (var i=0;i<=20;i++) {
      // this.type = this.getExperimentTypes().response.data.rows
      getExperimentTypes().then(response => {
        this.type = response.data.rows
        //this.$message.warning(this.getExperimentTypes().response.data.rows)
      })
    },
    methods: {

      fetchData() {
        this.listLoading = true
        getFieldList({ 'shotId': this.GLOBAL.shot.shotId }).then(response => {
          const limit = 10
          //  在前端做的一个分页查询，显示部分数据；
          const pageList = response.data.rows.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          this.total = response.data.total
          this.data = pageList
          this.listLoading = false
        })
      },

      handleDownload(type) {
        let date = new Date();
        let fileName = 'PartADataManage-' + date.getFullYear() + '-' + date.getMonth() + '-' + date.getDay() + '-' + date.getHours() + '-' + date.getMinutes();
        let tHeader = ['试验田序号Test', '试验田名称Test', '试验类型Test'];
        let filterVal = ['fieldId', 'name', 'experimentName'];
        switch (type) {
          case 'base':
            this.baseDownloadLoading = true;
            this.download(
              'PartADataManage-Base',
              ['试验田序号Test', '试验田名称Test', '试验类型Test'],
              ['fieldId', 'name', 'experimentName'],
              this.baseUpload
            )
            break
          case 'batch':
            this.batchDownloadLoading = true
            this.download(fileName, tHeader, filterVal, this.sels)
            break
          case 'all':
            this.allDownloadLoading = true
            let para = {
              key: this.filters.key,
              page: -1
            }
            getFieldList({ 'shotId': this.GLOBAL.shot.shotId} ).then((res) => {
              this.download(fileName, tHeader, filterVal, res.data.data)
            })
            break
        }
      },
      download(fileName, tHeader, filterVal, dataList) {
        require.ensure([], () => {
          const {
            export_json_to_excel
          } = require('vendor/Export2Excel')
          const data = this.formatJson(filterVal, dataList)
          export_json_to_excel(tHeader, data, fileName)
        })
        this.allDownloadLoading = false
        this.batchDownloadLoading = false
        this.baseDownloadLoading = false
      },
      // 参数过滤
      formatJson(filterVal, jsonData) {
        console.log(jsonData)
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      // 上传成功后的回调
      uploadSuccess(res, file, fileList) {
        this.uploadLoading=false
        this.listLoading=false
        if (res.code === 200) {
          this.$message({
            message: res.message,
            type: 'success'
          });
          this.getData()
        } else {
          this.$message({
            message: res.message ? res.message : '上传失败，服务器出错!',
            type: 'error'
          })
        }
      },
      // 上传错误
      uploadError(res, file, fileList) {
        this.uploadLoading=false
        this.listLoading=false
        this.$message({
          message: '上传失败，服务器出错!',
          type: 'error'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload(file) {
        this.listLoading=true
        this.uploadLoading=true
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.listLoading=false
          this.uploadLoading=false
          this.$message({
            showClose: true,
            message: '上传模板只能是xlsx格式!',
            type: 'error'
          })
        }
        if (!isLt2M) {
          this.uploadLoading=false
          this.listLoading=false
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!',
            type: 'error'
          })
        }
        return extension && isLt2M
      },
      setUploadAction(){
        let user = sessionStorage.getItem('user')
        this.uploadAction = 'http://api.com/data?access_token'+user.access_token
      }
    },
    // mounted() {
    //   this.getData();
    //   this.setUploadAction();
    // }
  }

</script>
